package com.zhonghui.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.zhonghui.common.core.result.FwResult;
import com.zhonghui.common.core.utils.JwtUtils;
import com.zhonghui.common.core.utils.RedisUtils;
import com.zhonghui.dto.AccountLoginDto;
import com.zhonghui.mapper.AdminMapper;
import com.zhonghui.model.Admin;
import com.zhonghui.service.AdminService;
import com.zhonghui.dto.PhoneLoginDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static com.zhonghui.common.core.constant.FwConstants.ADMIN_LOGIN_TOKEN;

/**
 * @author: FL
 * @create: 2024 2024/6/18 8:41
 */
@Service
@Slf4j
public class AdminServiceImpl implements AdminService {

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    private JwtUtils jwtUtils;
    @Override
    public FwResult<Map<String, Object>> login(AccountLoginDto accountLoginDto) {

        Admin user = adminMapper.selectAdminByAccount(accountLoginDto.getAccount());
        if(ObjectUtil.isNotNull(user)){
            if(user.getPassword().equals(SecureUtil.md5(accountLoginDto.getPassword()))   ){
                Map<String,Object> map=new HashMap<>();
                String adminCache = JSONUtil.toJsonStr(user);
                redisUtils.set("userId",user.getId().toString(),360000);
                map.put("userInfo",user);
                String key= jwtUtils.sign(map);
                redisUtils.set(ADMIN_LOGIN_TOKEN +key,adminCache,360000);
                map.put("Authorization",key);
                return FwResult.ok(map);
            }else{
                return FwResult.failedMsg("密码错误");
            }
        }
        return FwResult.failedMsg("认证错误");
    }

    @Override
    public FwResult<Admin> logout(String token) {
        if(StrUtil.isNotBlank(token)){
            redisUtils.del(ADMIN_LOGIN_TOKEN+token);
        }
        return FwResult.okMsg("退出成功");
    }
}
